package org.ziegler.javabase.thread.exchanger;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang3.RandomUtils;

public class TestExchanger {

    static ExecutorService executorService = Executors.newCachedThreadPool();

    public static void main(String[] args) {

        Exchanger<List<Integer>> exchanger = new Exchanger<>();

        List<Integer> empty = new ArrayList<>();
        List<Integer> full = new ArrayList<>();

        executorService.submit(() -> {
            List<Integer> curList = empty;

            while (curList != null) {

                sleep(3000);

                for (int i = 0; i < 5; i++) {
                    curList.add(RandomUtils.nextInt(0, 100));
                }

                try {
                    curList = exchanger.exchange(curList);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        executorService.submit(() -> {
            List<Integer> curList = full;

            while (curList != null) {

                try {
                    curList = exchanger.exchange(curList);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("curList = " + curList.size());
                curList.forEach(i -> System.out.println("i = " + i));
                curList.clear();
            }
        });

        executorService.shutdown();
    }

    static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}
